package com.shaoshaohuo.app.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.PayWayAdapter;
import com.shaoshaohuo.app.entity.AlipayEntity;
import com.shaoshaohuo.app.entity.FragmentNewCarEntity;
import com.shaoshaohuo.app.entity.WxPayEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.PayUtils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class CommitPayOrder extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    /**
     * tobar
     */
    private ImageView order_tobar_back;
    private TextView order_tobar_enter;
    private ImageView order_tobar_right;
    private LinearLayout order_layout_topbar_left;
    /**
     * 支付方式
     */
    private ListView commit_pay_way;
    private List<String> commit_pay_way_list;
    private PayWayAdapter commit_pay_adapter;
    private List<Integer> commit_pay_picture_list;

    private boolean isSelect = true;
    private Button commit_pay_button;

    private String fin_money = "";
    private String orderid = "";
    private TextView commit_pay_money;

    private int type = 1;
    private MyBrocasrReciver myBrocasrReciver;
    private List<FragmentNewCarEntity.DataBean> sure_order_shop_data;

    public CommitPayOrder newInstance(Intent intent, String money, String orderid) {
        CommitPayOrder commitPayOrder = new CommitPayOrder();
        Bundle bundle = new Bundle();
        bundle.putString("fin_money", money);
        bundle.putString("orderid", orderid);
        intent.putExtras(bundle);
        return commitPayOrder;
    }

    public void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            orderid = bundle.getString("orderid");
            fin_money = bundle.getString("fin_money");
            sure_order_shop_data = (List<FragmentNewCarEntity.DataBean>) bundle.getSerializable("shop_data");
        }
        Log.e("CommitPayOrde", orderid + "==" + fin_money);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commit_pay_order);
        getIntentData();
        myBrocasrReciver = new MyBrocasrReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("finsh");
        registerReceiver(myBrocasrReciver, intentFilter);
        Log.e("支付总钱数", fin_money + "");
        initView();
        getdata();
        bindAdapter();
        initListener();
    }

    private void initListener() {
        commit_pay_way.setOnItemClickListener(this);
        commit_pay_button.setOnClickListener(this);
        order_tobar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(0x0001, intent);
                finish();
            }
        });
    }

    private void bindAdapter() {
        commit_pay_way.setAdapter(commit_pay_adapter);
    }

    private void getdata() {
        commit_pay_way_list.add("请选择支付方式");
        commit_pay_way_list.add("支付宝支付");
        commit_pay_way_list.add("微信支付");
        commit_pay_picture_list.add(R.drawable.zhifubao);
        commit_pay_picture_list.add(R.drawable.weixin);
        commit_pay_adapter = new PayWayAdapter(this, commit_pay_way_list, commit_pay_picture_list);
    }

    private void initView() {
        /**
         * tobar
         * */
        order_tobar_back = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        order_tobar_back.setVisibility(View.VISIBLE);
        order_tobar_back.setImageResource(R.mipmap.return_key);
        order_tobar_enter = (TextView) findViewById(R.id.toolbar_topname);
        order_tobar_enter.setText("提交订单");
        order_tobar_right = (ImageView) findViewById(R.id.imageview_message);
        order_tobar_right.setVisibility(View.GONE);
        order_layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        order_layout_topbar_left.setVisibility(View.VISIBLE);

        commit_pay_way = (ListView) findViewById(R.id.commit_pay_way);
        commit_pay_way_list = new ArrayList<>();
        commit_pay_picture_list = new ArrayList<>();
        commit_pay_money = (TextView) findViewById(R.id.commit_pay_money);
        commit_pay_button = (Button) findViewById(R.id.commit_pay_button);
        commit_pay_money.setText("￥" + fin_money);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        ImageView imageView = (ImageView) view.findViewById(R.id.pay_way_select);
//        commit_pay_way.setSelection(position);
        commit_pay_adapter.selectItemState(position);
        commit_pay_adapter.notifyDataSetChanged();
        if (position == 1) {
            type = 1;
        } else if (position == 2) {
            type = 2;
        }
//        if (imageView.isSelected()) {
//            isSelect = false;
//        } else {
//            commit_pay_way.setSelected(false);
//            isSelect = true;
//            imageView.setSelected(isSelect);
//        }
//        commit_pay_way_list.get(position);
    }

    @Override
    public void onClick(View v) {
//取得是那种支付方式,然后提交
//        Map<String, String> map_head = RequestParam.getHeaderParams();
//        map_head.put("userid", "32235");
//        map_head.put("usertoken", "de18XVCd01a5Fd3RaipsGgsQMMg6gx3fqtWPXyCnHC1jT7HQmBe2K1%2BgBhTkGoORSgt9E8juKvHvczk1nyHP2pcCYCw2ur0VDC9n5VOmtEcUg0r4CnTm99aHghzETYcVyOjQFD8KLjHa2emKSynjw5tKUMkdokNWe9C1C4amrBbpo7nQdjZ%2BZCQUoY2nOC%2FS%2B0AV5GPUehx2JXtmmtirRJRJhG%2FjkSh5dVob53ckVX0rIBfeTBM%2Fk6%2FUXrjs1RJzRJHiD%2BFWrMkDVoBEx9L%2Bq7wSdXb9Fg0V%2BAST1jRxfcXTtasLJix1jtn6wcxJPRdccAXzevNsw%2F5x5kr66h3F9kKkYo1y7FNUVd3Pt9hO57LM6IEOqCTbiyOSvS09on5r%2BDqIl6pmN7%2BkoElDntI7aQ");
        if (type == 1) {
            //支付宝
            Log.e("TAG", "onClick: " + orderid + "=====" + fin_money);
            ShopHttpConfig.Apppay(this, type + "", orderid, fin_money, new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {

                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    AlipayEntity alipayEntity = (AlipayEntity) o;
                    AlipayEntity.DataBean data = alipayEntity.getData();
                    String sign = data.getSign();
                    //发起支付宝请求
                    PayUtils.payzfb(CommitPayOrder.this, sign, new PayUtils.PayListener() {
                        @Override
                        public void Success() {
                            CommitPayOrder.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toast("支付成功");
                                    Intent intent = new Intent();
                                    long l = new Date().getTime();
                                    intent.putExtra("time", l);
                                    intent.putExtra("orderid", orderid);
                                    intent.putExtra("shop_data", (Serializable) sure_order_shop_data);
                                    intent.putExtra("totalmoney", fin_money);
                                    intent.setClass(CommitPayOrder.this, FinishPayMoney.class);
                                    startActivity(intent);
                                    Intent intent1 = new Intent();
                                    intent1.setAction("finsh");
                                    sendBroadcast(intent1);
                                    finish();
                                }
                            });

                        }

                        @Override
                        public void Erro(final String result) {
                            CommitPayOrder.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.toast("支付失敗" + result);
                                    Log.e("TAG", "run: " + result);
                                }
                            });


                        }
                    });
                }
            }, AlipayEntity.class);
        } else {
            //微信
            ShopHttpConfig.Apppay(this, "2", orderid, fin_money, new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {

                }

                @Override
                public void suseff(Call call, Response response, final Object o) {
                    final WxPayEntity wxPayEntity = (WxPayEntity) o;
                    final String appid = wxPayEntity.getData().getAppid();
                    final WxPayEntity.DataBean data = wxPayEntity.getData();
                    CommitPayOrder.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String sign = data.getSign();
                            String partnerid = data.getPartnerid();
                            String prepayid = data.getPrepayid();
                            String noncestr = data.getNoncestr();
                            String timestamp = data.getTimestamp();

                            PayUtils.wxpay(CommitPayOrder.this, sign, appid, partnerid, prepayid, noncestr, timestamp,orderid);

                        }
                    });

                }
            }, WxPayEntity.class);

        }
    }

    public class MyBrocasrReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("finsh")) {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBrocasrReciver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0x0001, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
